<?php

namespace Lib;

final class Msgcode {

    /**
     * @desc 生成短信验证码
     *
     * @param $mobile
     * @return int
     */
    public static function create($mobile, $channel) {
        $key   = sprintf(\Lib\Consts::MOBILEPHONE_MESSAGECODE, md5(implode(':', array($channel, $mobile))));
        $code  = mt_rand(1000, 9999);
        $redis = \Yaf\Registry::get('redis');
        $redis->set($key, $code);
        $redis->expire($key, \Lib\Consts::EXPIRE_15MINU);

        return $code;
    }

    /**
     * @desc 短信验证码校验
     *
     * @param $mobile
     * @param $code
     * @return bool
     */
    public static function verify($mobile, $channel, $code) {
        $key    = sprintf(\Lib\Consts::MOBILEPHONE_MESSAGECODE, md5(implode(':', array($channel, $mobile))));
        $redis  = \Yaf\Registry::get('redis');
        $source = $redis->get($key);
        $redis->del($key);

        return !!$code && !!$source && 0 === strcmp($code, $source);
    }

}
